import sqlite3
import os
import csv

DB_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "train.db")
CSV_FILE = "最新报名.csv"

def get_db_connection():
    conn = sqlite3.connect(DB_FILE)
    conn.row_factory = sqlite3.Row
    return conn

def list_enroll_data():
    conn = None
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT name, company, position, price, status, phone, email FROM enroll")
        rows = cursor.fetchall()

        if rows:
            print("Enroll Table Contents:")
            # 指定CSV头部为选择的列名（中文）
            headers = ['姓名', '公司', '岗位职务', '价格','订单状态','电话', '邮箱']
            
            with open(CSV_FILE, 'w', newline='', encoding='utf-8') as csvfile:
                csv_writer = csv.writer(csvfile)
                csv_writer.writerow(headers)  # 写入头部
                for row in rows:
                    csv_writer.writerow([row['name'], row['company'], row['position'], row['price'], row['status'], row['phone'], row['email']])  # 写入每一行数据
            print(f"数据已成功导出到 {CSV_FILE}")
        else:
            print("No entries found in the enroll table.")
    except sqlite3.Error as e:
        print(f"Database error: {e}")
    except IOError as e:
        print(f"File I/O error: {e}")
    finally:
        if conn:
            conn.close()

if __name__ == "__main__":
    list_enroll_data()
